<script setup lang="ts">
import { ref, defineProps, defineEmits } from 'vue'

// 登录组件
const props = defineProps<{
  users: { username: string; password: string; createdAt: number }[]
  errorMsg: string
}>()

const emit = defineEmits<{
  (e: 'loginSuccess', username: string): void
  (e: 'toRegister'): void
  (e: 'clearError'): void
  (e: 'setError', msg: string, isSuccess?: boolean): void
}>()

const loginForm = ref({ username: '123456', password: '123456' })

const handleLogin = () => {
  emit('clearError')
  const { username, password } = loginForm.value
  const trimedName = username.trim()
  const trimedPwd = password.trim()

  if (!trimedName || !trimedPwd) {
    emit('setError', '用户名和密码不能为空！')
    return
  }

  const isDefaultAccount = trimedName === '123456' && trimedPwd === '123456'
  
  const matchedUser = props.users.find(
    u => u.username === trimedName && u.password === trimedPwd
  )

  if (isDefaultAccount || matchedUser) {
    emit('loginSuccess', trimedName) 
    loginForm.value = { username: '', password: '' } 
  } else {
    emit('setError', '用户名或密码错误！')
  }
}
</script>

<template>
  <div class="auth-page">
    <div class="auth-card">
      <div class="auth-icon">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#6366f1" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/>
          <path d="M14 2v4a2 2 0 0 0 2 2h4"/>
          <circle cx="10" cy="13" r="2"/>
          <path d="M20 17a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-1a2 2 0 0 1 2-2h1a2 2 0 0 1 2 2v1Z"/>
        </svg>
      </div>
      <h2 class="auth-title">欢迎登录 TodoList</h2>
      <div class="auth-form">
        <div class="form-group">
          <label class="form-label">用户名</label>
          <input
            type="text"
            class="form-input"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            autocomplete="off"
            @focus="emit('clearError')"
          />
        </div>
        <div class="form-group">
          <label class="form-label">密码</label>
          <input
            type="password"
            class="form-input"
            v-model="loginForm.password"
            placeholder="请输入密码"
            @focus="emit('clearError')"
          />
        </div>
        <p class="error-msg" v-if="errorMsg">{{ errorMsg }}</p>
        <div class="auth-btns">
          <button class="auth-btn primary" @click="handleLogin">登录</button>
          <div class="auth-switch">
            还没有账号？
            <button class="auth-link" @click="emit('toRegister')">去注册</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>